<template>
  <view>
    <u-cell-group>
      <u-cell title="头像" :title-style="titleStyle">
        <u-avatar slot="value" :src="userInfo.avatar" @click="upLoadAvatar" />
      </u-cell>
      <u-cell title="昵称" :title-style="titleStyle">
        <u-input
          v-model="userInfo.nickname"
          slot="value"
          placeholder="输入昵称"
          suffix-icon="arrow-right"
          suffix-icon-style="color: #909399"
          border="none"
          font-size="13px"
          input-align="right"
        />
      </u-cell>
    </u-cell-group>
    <view class="btn">
      <u-button
        type="primary"
        shape="circle"
        text="确认修改"
        :throttleTime="1000"
        @click="handleSubmit"
      />
    </view>
  </view>
</template>

<script>
import { userProfile, commonUpload } from "@/request/api.js";
export default {
  data() {
    return {
      avatar: "", // 头像
      nickname: "", // 昵称
      userInfo: {},
      titleStyle: {
        fontFamily: "PingFang SC",
        fontStyle: "normal",
        fontWeight: 400,
        fontSize: "14px",
        lineHeight: "22px",
        color: "#222222",
      },
    };
  },
  created() {
    this.init();
  },
  methods: {
    // 初始化用户信息
    init() {
      let info = uni.getStorageSync("USER_INFO");
      if (info) {
        this.userInfo = JSON.parse(info);
      }
    },
    // 提交修改
    handleSubmit() {
      if (!this.userInfo.avatar) {
        uni.showToast({
          title: "头像不能为空",
          icon: "none",
        });
        return;
      }
      if (!this.userInfo.nickname) {
        uni.showToast({
          title: "昵称不能为空",
          icon: "none",
        });
        return;
      }
      let data = {
        token: uni.getStorageSync("TOKEN"),
        nickname: this.userInfo.nickname,
        avatar: this.userInfo.avatar,
      };
      userProfile(data).then((res) => {
        if (res.code == 1) {
          uni.showToast({
            title: "修改成功",
            icon: "success",
            mask: true,
            success: () => {
              uni.setStorageSync("USER_INFO", JSON.stringify(res.data.userinfo));
              setTimeout(() => {
                uni.navigateBack({ delta: 1 });
              }, 2000);
            },
          });
        }
      });
    },
    // 上传头像
    upLoadAvatar() {
      uni.chooseImage({
        count: 1, // 单选
        sizeType: ["original"],
        sourceType: ["album", "camera"], //相册 相机
        success: (res) => {
          commonUpload(res.tempFilePaths[0]).then((res) => {
            if (res.code == 1) {
              this.userInfo.avatar = res.data.fullurl;
            }
          });
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.btn {
  position: fixed;
  bottom: 100rpx;
  left: 30rpx;
  right: 30rpx;
}
</style>
